package com.hgvip.service;

import com.hgvip.util.RedisDistributedLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author arnold.zhu
 * @date 2018/4/4
 */
@Service
public class TestService {

    private Logger logger = LoggerFactory.getLogger(TestService.class);

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    private RedisDistributedLock redisDistributedLock;

    public void doSomething() {
        initLock();
        boolean flag = redisDistributedLock.lock("redis-lock:myLock");
        // 加锁失败后 可以做对应的业务处理
        if (flag) {
            logger.info(Thread.currentThread().getId() + " 加锁成功");
            // 加锁成功后 休眠5秒 模拟某些需要加锁的耗时操作
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            redisDistributedLock.releaseLock("redis-lock:myLock");
            logger.info(Thread.currentThread().getId() + " 释放锁");
        } else {
            logger.info(Thread.currentThread().getId() + " 加锁失败");
        }
    }

    private void initLock() {
        if (redisDistributedLock == null) {
            redisDistributedLock = new RedisDistributedLock(redisTemplate);
        }
    }
}
